/**
 * Created by liuqingxia on 2016/7/26.
 */

var taskTable;
var taskTableWithParam;
var currRmTaskId;//当前要删除的task的Id

/**
 * main入口
 */
$(document).ready(function () {


    LTS.colFormatter.optFormat = function (v, row) {
        return generateOptButtons(row);
    }

    LTS.colFormatter.moveMode = function (v, row) {
        return moveMode(row);
    }

    LTS.colFormatter.stateFormat = function (v, row) {
        return stateFormat(row);
    }

    taskTable = $("#task-table-container").ltsTable({
        url: getUrlBySuffix("/yugong/task/find"),
        templateId: 'task-table'
    });

    taskTableWithParam = $("#task-table-container").ltsTable({
        url: getUrlBySuffix("/yugong/task/findByTableName"),
        templateId: 'task-table'
    });

    taskTable.post({}, 1);

    clickStartBtn();
    clickRemoveBtn();
    clickConfirmRemoveBtn();
    clickUpdateBtn();
    clickConfirmUpdateBtn();
    clickSearchBtn();
    clickSearchAllBtn();

    clickStopBtn();

    clickLogQueryBtn();

});

/**
 * 任务状态
 * @param row
 */
function stateFormat(row) {
	var state = row['state'];
	if(state =="0"){
		return "未运行";
	}
    return "运行中";
}

/**
 * 运行模式
 * @param row
 */
function moveMode(row) {

    var moveInt = row['moveMode'];
    var result = "";

    switch (moveInt) {
        case 1:
            result = "MARK";
            break;
        case 2:
            result = "INC";
            break;
        case 3:
            result = "FULL";
            break;
        case 4:
            result = "ALL";
            break;
        case 5:
            result = "CHECK";
            break;
        case 6:
            result = "CLEAR";
            break;
        default:
            result = "未识别";
    }

    return result;

}

/**
 * 生成操作按钮
 * @param row
 * @returns {string}
 */
function generateOptButtons(row) {
	var state = row['state'];
	var optButtons;
	if(state=="0"){
		optButtons = "" + removeBtn + updateBtn + "" + '<a href="javascript:;" class="start-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-play"></i>&nbsp;&nbsp;' +
        '启动任务' +
        '</span>' +
        '</a>&nbsp;' + "" +
        '<a href="javascript:;" class="queryLog-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-file"></i>&nbsp;&nbsp;' +
        '查看日志' +
        '</span>' +
        '</a>&nbsp;';
	}else{
		optButtons = "" + removeBtn + updateBtn + "" +
        '<a href="javascript:;" class="stop-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-stop"></i>&nbsp;&nbsp;' +
        '停止任务' +
        '</span>' +
        '</a>&nbsp;' +
        '<a href="javascript:;" class="queryLog-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-file"></i>&nbsp;&nbsp;' +
        '查看日志' +
        '</span>' +
        '</a>&nbsp;';
	}
    return optButtons;
}

/**
 * 点击停止按钮
 */
function clickStopBtn() {
    $(document).on("click", ".stop-btn", function () {
        var currentId = getCurrentId($(this));
        // console.log(currentId);
        $.postHttpSync({id: currentId}, getUrlBySuffix("/yugong/task/stop"), function(json){
        	if (json && json.success) {
                swal({
    				title : "操作成功",
    				text : json['message'],
    				type : "success"
    			}, function() {
    				var tableName = $.trim($("#tableNameInp").val());
               	 	if (tableName=="") {
               	 		taskTable.post({}, pageNum);
                    }else{
                        taskTableWithParam.post({tableName: tableName}, pageNum);
                    }
    			});
            } else {
                if (json) {
                    swal("失败", json['message'], 'error');
                }
            }
        });
    });
}

/**
 * 点击当前"启动任务按钮"
 */
function clickStartBtn() {
    $(document).on("click", ".start-btn", function () {
        var currentId = getCurrentId($(this));
        // console.log(currentId);
        $.postHttpSync({id: currentId}, getUrlBySuffix("/yugong/task/start"), function(json){
        	if (json && json.success) {
                swal({
    				title : "操作成功",
    				text : json['message'],
    				type : "success"
    			}, function() {
    				var tableName = $.trim($("#tableNameInp").val());
               	 	if (tableName=="") {
               	 		taskTable.post({}, pageNum);
                    }else{
                        taskTableWithParam.post({tableName: tableName}, pageNum);
                    }
    			});
            } else {
                if (json) {
                    swal("失败", json['message'], 'error');
                }
            }
        });
    });
}


/**
 * 点击删除按钮
 */
function clickRemoveBtn() {
    $(document).on("click", ".remove-btn", function () {
        currRmTaskId = getCurrentId($(this));
        $("#remove-tip-modal").modal("show");
    });
}

/**
 * 点击确认删除按钮
 */
function clickConfirmRemoveBtn() {
    $(document).on("click", "#confirm-remove-btn", function () {
        $("#cancel-remove-btn").trigger("click");//提示框隐藏
        var params = {};
        params['id'] = $.trim(currRmTaskId);
        $.postHttpSync(params, getUrlBySuffix("/yugong/task/remove"), function(json){
        	if (json && json.success) {
        		swal({
    				title : "操作成功",
    				text : json['message'],
    				type : "success"
    			}, function() {
    				var tableName = $.trim($("#tableNameInp").val());
               	 	if (tableName=="") {
               	 		taskTable.post({}, pageNum);
                    }else{
                        taskTable.post({}, 1);
                    }
               	 $("#remove-tip-modal").modal("hide");
    			});
               	
            } else {
                if (json) {
                    swal("失败", json['message'], 'error');
                }
            }
        });
    });
}

/**
 * 点击编辑按钮
 */
function clickUpdateBtn() {
    $(document).on("click", ".update-btn", function () {
        var id = getCurrentId($(this));
        // console.log(id);
        var ygTask = getObjectById(getUrlBySuffix("/yugong/task/findById"), id);
        // console.log("ygTask: " + JSON.stringify(ygTask));
        fillTaskEditForm(ygTask);//将dataSource对象各属性值赋值到任务编辑表单
        $("#task-edit-modal").modal("show");//显示任务编辑模态框
    });
}

/**
 * 把对象的各属性赋值到编辑表格中
 * @param obj
 */
function fillTaskEditForm(obj) {
    $.each($('#editForm').parent().find(".form-control"), function () {

        var name = $.trim($(this).attr("name"));

        if (isNull(name)) {
            return true;
        }
        var value = $.trim(obj[name]);
        $(this).val(value);
    });
}

/**
 * 点击任务编辑模态框上的修改按钮
 */
function clickConfirmUpdateBtn() {
    $(document).on("click", "#edit-btn", function () {
        var params = getFormParams("editForm");
        // console.log("json:" + JSON.stringify(params));
        $.postHttp(params, getUrlBySuffix("/yugong/task/update"), function(json){
        	if (json && json.success) {
                swal({
    				title : "操作成功",
    				text : json['message'],
    				type : "success"
    			}, function() {
    				var tableName = $.trim($("#tableNameInp").val());
    				if (tableName=="") {
               		 	taskTable.post({}, pageNum);
                    }else{
                        taskTableWithParam.post({tableName: tableName}, pageNum);
                    }
    				$("#task-edit-modal").modal("hide");
    			});
            } else {
                if (json) {
                    swal("失败", json['message'], 'error');
                }
            }
        });
        $("#task-edit-modal-dismiss").modal("hide");
        // $("#searchBtn").trigger("click");
    });
}

/**
 * 点击搜索按钮
 */
function clickSearchBtn() {
    $(document).on("click", "#searchBtn", function () {
        var tableName = $.trim($("#tableNameInp").val());
        // console.log("tableName:" + tableName);
        taskTableWithParam.post({tableName: tableName}, 1);
    });
}

/**
 * 点击"搜索全部"按钮
 */
function clickSearchAllBtn() {
    $(document).on("click", "#searchAllBtn", function () {
        taskTable.post({}, 1);
    });
}

var readLogFileIntervalId;
var currentId;
var logFileBeginIndex = 0;
var readEndCount = 0;
var executeIp;
var ygTaskLogPre = "ygTask-log-pre";
var ygTaskLogModal = "ygTask-log-modal";

/**
 * 点击日志查询按钮
 */
function clickLogQueryBtn() {

    $(document).on("click", ".queryLog-btn", function () {

        currentId = getCurrentId($(this));
        // console.log("currentId:" + currentId);
        executeIp = $.trim(findYgManagerIPByTaskId(currentId)) + ":8081";
        // console.log("ygManagerIp:" + executeIp);

        if (typeof readLogFileIntervalId != "undefined") {/*虽然关闭模态框时，已经关闭定时任务，但此处还是有必要*/
            closeReadFileInterval(readLogFileIntervalId);
        }
        emptyLogContent();
        $("#" + ygTaskLogModal).modal("show");
        readLogFileIntervalId = self.setInterval("readLogFileInterval(currentId)", 1000);
        console.log("readLogFileIntervalId:" + readLogFileIntervalId);

    });
}


/**
 * 根据id查找YgManager的ip
 * @param id
 */
function findYgManagerIPByTaskId(id) {
    var ip;
    $.postHttpSync({id: id}, getUrlBySuffix("/yugong/task/findYgManagerByTaskId"), function (json) {
        if (json && json.success) {
            ip = json['list'][0];
        }
    });
    return ip;
}

/**
 * 关闭读取日志文件定时任务
 * @param id
 */
function closeReadFileInterval(id) {
    window.clearInterval(readLogFileIntervalId);
    logFileBeginIndex = 0;
}

/**
 * 关闭模态框
 */
function closeModal() {
    $(document).on("click", "button.close", function () {
        closeReadFileInterval(readLogFileIntervalId);
    });
}

/**
 * 定时读取日志文件
 *
 * @param id
 */
function readLogFileInterval(id) {
    readLogFile(id, logFileBeginIndex);
    return;
}

/**
 * 异步显示日志文件
 * @param resultMap
 */
function asyncReadLogFile(resultMap) {

    var errorMsg = resultMap['errorMsg'];
    if (!isNull(errorMsg)) {
        closeReadFileInterval(readLogFileIntervalId);
        showErrorMsg(errorMsg);
        return;
    }

    if (resultMap['beginIndex'] == -2) {
    	closeReadFileInterval(readLogFileIntervalId);
        return;
    }

    logFileBeginIndex = resultMap['beginIndex'];
    var logContent = resultMap['result'];
    showLogContentAtEnd(logContent);
}

/**
 * 在日志显示区添加新读取到的内容
 * @param logContent
 */
function showLogContentAtEnd(logContent) {
    $("#" + ygTaskLogPre).append(logContent);
}

/**
 * 显示错误信息
 */
function showErrorMsg(errorMsg) {
    $("#" + ygTaskLogPre).append("<br><span style='color: red;font-weight: 900'>" + errorMsg + "</span>");
}

/**
 * 清空日志显示区
 */
function emptyLogContent() {
    $("#" + ygTaskLogPre).empty();
}


/**
 * 读取日志文件内容
 * @param id,记录日志Id
 * @param beginIndex,文件读取位置
 */
function readLogFile(id, beginIndex) {
    var resultMap = {};
    $.ajax({
        type: "get",
        url: "http://" + executeIp + "/datax-console/api/yugong/log?id=" + id + "&beginIndex=" + beginIndex,
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (json) {
            $.extend(resultMap, json);
            asyncReadLogFile(resultMap);
        }
    });
}


